<?php

namespace app\model\v1\recovery;

use app\model\user\User;
use crmeb\traits\ModelTrait;
use think\exception\ValidateException;
use think\Model;

class RecoveryUserSearchHistory extends Model
{
    use ModelTrait;


    protected $updateTime = false;
    protected $createTime = false;

    public function user()
    {
        return $this->hasOne(User::class, 'uid', 'uid');
    }



    /**
     * 获取用户历史搜索
     * @param $uid
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function getUserSearchHistory($uid='', $param)
    {
        //获取用户的历史搜索数据最新的前十条
        return self::where('uid', $uid)
	        ->where ('topic', $param['topic'])
            ->where(function($query) use ($param){
                if(!empty($param["keyword"])){
                    $query->where('keyword', 'like', '%'.$param["keyword"].'%');
                }
            })
            //->limit(10)
            ->order('id','desc')
            ->select()->toArray();
    }


    /**
     * 用户历史搜索删除
     * @param array $param
     * @param $topic
     * @return bool|int
     */
    public static function deleteSearch($param=[])
    {
        if (!empty($param['all'])) {
            return RecoveryUserSearchHistory::where(['uid' => $param['uid'], 'topic' => $param['topic']])->delete();
        } else {
            if (empty($param['id'])) {
                throw new ValidateException('参数错误');
            }
            return RecoveryUserSearchHistory::where(['id' => $param['id'], 'uid' => $param['uid'], 'topic' => $param['topic']])->delete();
        }
    }

}